#coding=utf-8
from stutils import *
set_django_environ()
from stdj.stock.models import *

def prices_on(exdate):
    from django.db import connection
    c = connection.cursor()
    c.execute( 'select id from stock_exday where date=%s', (exdate,) )
    
    r = c.fetchall()
    if not r:return None
    ids = [i[0] for i in r]
    
    ps = [ Exday.objects.get(pk=id).price for id in ids ]
    return ps 

def jayindex_change(exdate):
    ps = prices_on(exdate)
    n = len(ps)
    s = sum( [p.change for p in ps if p.change])/100
    return float(todec(s/n,2))

if __name__ == '__main__':
    from indexdb import get_exdayslist
    import pickle
    
    eds = get_exdayslist('2007-01-01')
    
    r = [1, ]
    pre = r[0]
    for e in eds[1:]:
        c = pre * ( 1 + jayindex_change(e))
        c = float(todec(c,2))
        r.append(c)
        pre = c
        
        print e,c
        
    fn  =  datadir + '/jayindex.pk'
    f = open(fn, 'w')
    pickle.dump(r, f) 
    